<template>
  <div>
    <el-form :model="borrowQueryForm" inline ref="queryRef">
      <el-form-item label="读者编号" prop="readerId">
        <el-input v-model="borrowQueryForm.readerId"></el-input>
      </el-form-item>
      <el-form-item label="图书编号" prop="bookId">
        <el-input v-model="borrowQueryForm.bookId"></el-input>
      </el-form-item>
      <el-form-item label="借阅状态" prop="status">
        <el-select v-model="borrowQueryForm.status" style="width: 240px">
          <el-option label="全部" :value="-1"></el-option>
          <el-option label="借出中" :value="0"></el-option>
          <el-option label="已归还" :value="1"></el-option>
          <el-option label="逾期" :value="2"></el-option>
          <el-option label="丢失" :value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getBorrowRecordsPage" icon="Search">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="queryRef.resetFields()" icon="Refresh">重置</el-button>
      </el-form-item>
    </el-form>
    <el-button type="primary" size="small" icon="Plus" @click="dialogVisible=true">新增</el-button>
    <el-button type="danger" size="small" icon="IconReturn" @click="batchReturn" :disabled="!selectedRowsCount">
      批量归还
    </el-button>
    <el-button type="danger" size="small" icon="IconReturn" @click="batchRenew" :disabled="!selectedRowsCount">
      批量续借
    </el-button>
    <el-table :data="borrowPage.list" v-loading="loading" ref="multipleTableRef">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="recordId" label="记录ID"></el-table-column>
      <el-table-column prop="bookId" label="图书编号"></el-table-column>
      <el-table-column prop="readerId" label="读者编号"></el-table-column>
      <el-table-column label="借阅时间">
        <template #default="scope">
          {{ $timeFormat(scope.row.borrowDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="dueDate" label="应还日期">
        <template #default="scope">
          {{ $timeFormat(scope.row.dueDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="returnDate" label="实际归还日期">
        <template #default="scope">
          {{ $timeFormat(scope.row.returnDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <span v-if="scope.row.status === 0">借出中</span>
          <span v-if="scope.row.status === 1">已归还</span>
          <span v-if="scope.row.status === 2">逾期</span>
          <span v-if="scope.row.status === 3">丢失</span>
        </template>
      </el-table-column>
      <el-table-column prop="renewCount" label="续借次数"></el-table-column>
      <el-table-column prop="operatorId" label="操作员ID"></el-table-column>
      <el-table-column prop="overdueDays" label="逾期天数"></el-table-column>
      <el-table-column label="操作" width="240">
        <template #default="scope">
          <el-button type="warning" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button type="danger" size="small">删除</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-dropdown>
            <el-button size="small" type="primary">
              更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item  @click="handleReturn(scope.row)">归还</el-dropdown-item>
                <el-dropdown-item @click="handleRenew(scope.row)">续借</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <div class="flex-end">
      <el-pagination
          background
          layout="prev, pager, next"
          :total="borrowPage.total"
          v-model:page-size="borrowQueryForm.pageSize"
          v-model:current-page="borrowQueryForm.pageNum"
      >
      </el-pagination>
    </div>

    <el-dialog
        v-model="dialogVisible"
        :title="isAdd? '新增借阅记录' : '修改借阅记录' "
        width="800"
        @close="closeHandel"
    >
      <el-form :model="borrowSaveForm" label-width="120px" inline ref="borrowSaveFormRef" :rules="rules">
        <el-form-item label="图书编号" prop="bookId">
          <el-input v-model="borrowSaveForm.bookId"></el-input>
        </el-form-item>
        <el-form-item label="读者编号" prop="readerId">
          <el-input v-model="borrowSaveForm.readerId"></el-input>
        </el-form-item>
        <el-form-item label="借阅时间" prop="borrowDate">
          <el-date-picker
              v-model="borrowSaveForm.borrowDate"
              type="datetime"
              placeholder="选择借阅时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="应还日期" prop="dueDate">
          <el-date-picker
              v-model="borrowSaveForm.dueDate"
              type="datetime"
              placeholder="选择应还日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="实际归还日期" prop="returnDate">
          <el-date-picker
              v-model="borrowSaveForm.returnDate"
              type="datetime"
              placeholder="选择实际归还日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="borrowSaveForm.status" style="width: 240px">
            <el-option label="借出中" :value="0"></el-option>
            <el-option label="已归还" :value="1"></el-option>
            <el-option label="逾期" :value="2"></el-option>
            <el-option label="丢失" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="续借次数" prop="renewCount">
          <el-input-number v-model="borrowSaveForm.renewCount"></el-input-number>
        </el-form-item>
        <el-form-item label="操作员ID" prop="operatorId">
          <el-input v-model="borrowSaveForm.operatorId"></el-input>
        </el-form-item>
        <el-form-item label="逾期天数" prop="overdueDays">
          <el-input-number v-model="borrowSaveForm.overdueDays"></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitSaveBorrow(borrowSaveFormRef)">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {computed, onMounted, reactive, ref, watch} from "vue";
import {ElMessage, ElMessageBox} from 'element-plus'
import {
  reqCreateBorrowRecord,
  reqGetBorrowRecordPage, reqRenewBook,
  reqReturnBook,
  reqUpdateBorrowRecord
} from "@/api/borrow-record/index.js"; // 这里的 API 路径请根据实际情况修改

// 查询条件表单数据
let borrowQueryForm = reactive({
  pageNum: 1,
  pageSize: 10,
  status: -1,
  bookId: '',
  readerId: ''
});
let multipleTableRef = ref()
// 保存表单数据
let borrowSaveForm = reactive({
  recordId: null,
  bookId: "",
  readerId: "",
  borrowDate: null,
  dueDate: null,
  returnDate: null,
  status: null,
  renewCount: 0,
  operatorId: null,
  overdueDays: null
});
let borrowSaveFormRef = ref();
let dialogVisible = ref(false);
let queryRef = ref();
let loading = ref(true);
let borrowPage = reactive({
  pageNum: 1,
  list: [],
  total: 0
});

// 是否是新增操作
let isAdd = ref(true);

// 获取借阅记录列表
let getBorrowRecordsPage = () => {
  reqGetBorrowRecordPage(borrowQueryForm).then((res) => {
    Object.assign(borrowPage, res.data);
    loading.value = false;
  });
};

// 编辑操作
let handleEdit = (node) => {
  Object.assign(borrowSaveForm, node);
  isAdd.value = false;
  dialogVisible.value = true;
};
let batchReturn = () => {
  let recordIds = multipleTableRef.value.getSelectionRows().map(item => item.recordId)
  ElMessageBox.confirm(
      '确定要归还选中的图书吗?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        reqReturnBook(recordIds)
      })
}
let batchRenew=() => {
  let recordIds = multipleTableRef.value.getSelectionRows().map(item => item.recordId)
  ElMessageBox.confirm(
      '确定要续借选中的图书吗?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        reqRenewBook(recordIds)
      })
}
// 关闭对话框时的处理
let closeHandel = () => {
  Object.assign(borrowSaveForm, {
    recordId: null,
    bookId: "",
    readerId: "",
    borrowDate: null,
    dueDate: null,
    returnDate: null,
    status: null,
    renewCount: 0,
    operatorId: null,
    overdueDays: null
  });
  isAdd.value = true;
};
const handleReturn = (recordId) => {
  ElMessageBox.confirm(
      '确定要归还这本书吗?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        reqReturnBook([recordId])
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: 'Delete canceled',
        })
      })
}
const handleRenew=(borrowRecord)=>{
  reqRenewBook([borrowRecord.recordId])
}

// 提交保存借阅记录
let submitSaveBorrow = async (formEl) => {
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (isAdd.value) {
        await reqCreateBorrowRecord(borrowSaveForm);
      } else {
        await reqUpdateBorrowRecord(borrowSaveForm);
      }
      await getBorrowRecordsPage();
      dialogVisible.value = false;
    } else {
      console.log('error submit!', fields);
    }
  });
};

// 表单验证规则
let rules = {
  bookId: [
    {required: true, message: '请输入图书编号', trigger: 'blur'},
  ],
  readerId: [
    {required: true, message: '请输入读者编号', trigger: 'blur'},
  ],
  borrowDate: [
    {required: true, message: '请选择借阅时间', trigger: 'blur'}
  ],
  dueDate: [
    {required: true, message: '请选择应还日期', trigger: 'blur'}
  ],
  status: [
    {required: true, message: '请选择状态', trigger: 'blur'}
  ],
  renewCount: [
    {required: true, message: '请输入续借次数', trigger: 'blur'}
  ],
  operatorId: [
    {required: true, message: '请输入操作员ID', trigger: 'blur'},
  ],
};
const selectedRowsCount = computed(() => {
  return multipleTableRef.value?.getSelectionRows()?.length || 0;
});
// 监听页码和页大小的变化，重新查询数据
watch([() => borrowQueryForm.pageNum, () => borrowQueryForm.pageSize], () => {
  getBorrowRecordsPage();
});

// 初始化时获取借阅记录列表和分类列表
onMounted(() => {
  getBorrowRecordsPage();
});
</script>

<style scoped>
/* 样式可以根据实际需求进行调整 */
</style>
